/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2024-04-26 13:43:27
 * @LastEditors: icymoon911 icymoon911@163.com
 * @LastEditTime: 2024-11-08 13:43:09
 * @FilePath: \ken147258.topayClient\src\utils\request.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios, { InternalAxiosRequestConfig, AxiosResponse } from "axios";
import { useUserStoreHook } from "@/store/modules/user";
import { getTimestamp } from "@/utils/index";
import router from "@/router";


const handleGetParams = (params: any) => {
  let result = { ...params };

  Object.entries(params || {}).map(([key, value]) => {
    if (value instanceof Date) {
      result[key] = getTimestamp(value);
    }
  });

  return result;
};

const handlePostParams = (params: any) => {
  if (params instanceof FormData) {
    return params;
  }

  let result = { ...params };

  Object.entries(params || {}).map(([key, value]) => {
    if (key === 'qr_code') {
      if (value) {
        const prefix = import.meta.env.VITE_APP_BASE_API;

        result[key] = value.toString().replace(new RegExp(prefix, 'g'), '');
      }
    }
  });

  return result;
};

// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  // baseURL: import.meta.env.VITE_APP_BASE_API_TEST,
  // baseURL: '',
  timeout: 50000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const userStore = useUserStoreHook();
    const loginType: string = userStore.getLoginType();
    const accessToken = localStorage.getItem(loginType + "accessToken");
    if (accessToken) {
      // config.headers.token = accessToken;

      // const loginForTwice: string = localStorage.getItem(loginType + "accessTokenTwice") || '';

      if (config.method?.toLowerCase() === 'get') {
        if (config.params) {
          config.params = handleGetParams(config.params);
        }
      } else if (config.method?.toLowerCase() === 'post') {
        if (config.data) {
          config.data = handlePostParams(config.data);
        }
      }

      if (loginType === 'web') {
        config.headers.Authorization = accessToken;
        // config.headers.platTwiceToken = loginForTwice;
      } else if (loginType === 'payee') {
        config.headers.skfToken = accessToken;
        // config.headers.msTwiceToken = loginForTwice;
      } else if (loginType === 'payer') {
        // config.headers.payerToken = accessToken;
      }
    }
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    // const { code, msg, data } = typeof (response.data) === 'string' ? JSON.parse(response.data) : response.data;
    const { code, msg, message, data } = response.data;

    if (code || msg || message || data) {
      console.log(
        'ReturnData',
        response.config.method,
        import.meta.env.VITE_APP_API_URL + response.request.responseURL.replace(window.location.origin + service.getUri()
          , ''),
        response.config.method?.toLowerCase() === 'get' ? response.config.data : (typeof (response.config.data) === 'string' ? JSON.parse(response.config.data || '{}') : response.config.data),
        data
      );

      if (["200", '0'].includes(code + '')) {
        return data;
      } else if ((code + '') === "203") {
        router.push({ path: '/login' });
      } else if ((code + '') === "301") {
        ElMessageBox.alert("当前页面已失效，请重新登录", "提示", {
          confirmButtonText: "确定",
          showClose: false,
          // type: "warning",
        }).then(() => {
          const userStore = useUserStoreHook();
          userStore.resetToken().then(() => {
            // location.reload();
          });

          return Promise.reject(new Error(msg || message || "Error"));
        });

        return Promise.reject(new Error(msg || message || "Error"));
      } else if ((code + '') === "302") {
        ElMessageBox.prompt('请验证安全码', '敏感操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern:
            /[\d,\w]{1,10}/,
          inputErrorMessage: '请输入正确的安全码',
        })
          .then(({ value }) => {
            // 访问网络验证安全码
            const userStore = useUserStoreHook();
            userStore.loginForTwice(value.trim()).then(() => {
              ElMessage
                .success('安全码验证成功');
            });
          })
          .catch(() => {
            ElMessage({
              type: 'info',
              message: '安全码输入错误',
            })
          });

        return Promise.reject(new Error(msg || message || "Error"));
      } else if ((code + '') === "303") {
        ElMessageBox.alert("请先绑定Google验证", "提示", {
          confirmButtonText: "确定",
          showClose: false,
        }).then(() => {
          router.push({ path: '/bind' });
        });

        return Promise.reject(new Error(msg || message || "Error"));
      } else if ((code + '') === "0") {
        ElMessage.error(msg || message || "系统出错");
        return Promise.reject(new Error(msg || message || "Error"));
      } else {
        // 响应数据为二进制流处理(Excel导出)
        if (response.data instanceof ArrayBuffer) {
          return response;
        }

        ElMessage.error(msg || message || "系统出错");
        return Promise.reject(new Error(msg || message || "Error"));
      }
    } else {
      return response.data;
    }
  },
  (error: any) => {
    if (error.response.status === 200) {
      if (error.response?.data) {
        console.log(
          error.config.method,
          'ReturnData Error',
          import.meta.env.VITE_APP_API_URL + error.response.request.responseURL.replace(window.location.origin + service.getUri()
            , ''),
          error.config.method?.toLowerCase() === 'get' ? error.config.data : JSON.parse(error.config.data || {}),
        );
        const { code, msg, message } = error.response.data;
        // token 过期,重新登录
        if (code === 301) {
          ElMessageBox.confirm("当前页面已失效，请重新登录", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            const userStore = useUserStoreHook();
            userStore.resetToken().then(() => {
              // location.reload();
            });
          });
        } else {
          ElMessage.error(msg || message || "系统出错");
          const userStore = useUserStoreHook();
          userStore.resetToken().then(() => {
            // // location.reload();
          });
        }
      }
    } else {
      ElMessage.error("系统出错");
      
      const userStore = useUserStoreHook();
      userStore.resetToken().then(() => {
        // location.reload();
      });
      
      return Promise.reject(error.message);
    }
  }
);

// 导出 axios 实例
export default service;
